package com.study.system.edusearchservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.edu.common.entity.Course;
import com.edu.common.entity.ElasticsearchEntity;
import com.edu.common.entity.PageEntity;
import com.study.system.edusearchservice.client.CourseServiceFeignClient;
import com.study.system.edusearchservice.dao.ElasticsearchDAO;
import com.study.system.edusearchservice.service.CourseIndexService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 课程索引服务实现类
 */
@Service
public class CourseIndexServiceImpl implements CourseIndexService {

    @Resource
    private ElasticsearchDAO dao;

    @Resource
    private CourseServiceFeignClient client;

    /**
     * 初始化课程索引
     * @throws IOException
     */
    @Override
    public void initCourseIndex() throws IOException {
        //如果索引存在，就删除
        if(dao.existsIndex(INDEX_NAME)){
            dao.deleteIndex(INDEX_NAME);
        }
        //创建课程索引
        dao.createIndex(INDEX_NAME);
        //调用课程服务获得所有课程信息
        List<Course> courses = client.getAllCourse().getBody();
        //创建ES实体类集合，添加课程对象
        List<ElasticsearchEntity> entities = new ArrayList<>();
        courses.forEach(course -> {
            entities.add(new ElasticsearchEntity((int) course.getId(),course));
        });
        //批量插入ES
        dao.insertBatch(INDEX_NAME,entities);
    }

    @Override
    public PageEntity searchCourse(Map<String, String> args) throws IOException {
        int current = 0,pageSize = 0;
        Map<String,String> search = new HashMap<>();
        Map<String,String> sort = new HashMap<>();
        //从map集合中解析搜索条件
        if(StringUtils.hasText(args.get("current") )){
            current = Integer.parseInt(args.get("current"));
        }
        if(StringUtils.hasText(args.get("size"))){
            pageSize = Integer.parseInt(args.get("size"));
        }
        if(StringUtils.hasText(args.get("search"))){
            search = JSON.parseObject(args.get("search"),Map.class);
        }
        if(StringUtils.hasText(args.get("sort"))){
            sort = JSON.parseObject(args.get("sort"),Map.class);
        }
        PageEntity pageEntity = dao.search(INDEX_NAME,current,pageSize,search,sort,Course.class,
                "courseName","brief");
        return pageEntity;
    }

    @Override
    public void saveCourse(Course course) throws IOException {
        dao.saveOrUpdate(INDEX_NAME,new ElasticsearchEntity(Integer.valueOf(String.valueOf(course.getId())),
                course));
    }

    @Override
    public void deleteCourse(Integer courseId) throws IOException {
        dao.deleteById(INDEX_NAME,String.valueOf(courseId));
    }
}
